package com.dubbo.spring;

import com.dubbo.utils.NetworkUtils;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.IOException;

/**
 * @author Zhuyanfeng on 2018/3/21
 */

@Configurable
public class DynamicPropertyConfigure {


    @Bean
    public PropertyPlaceholderConfigurer getInstance(){
        PropertyPlaceholderConfigurer c = new PropertyPlaceholderConfigurer();
        c.setLocation(getResource());
        return c;
    }

    private Resource getResource() {
        String path = null;
        Exception ex = null;
        for (int i=0;i<3;i++){
            try {
                path = getConfigurePath();
                break;
            } catch (IOException e) {
                ex = e;
            }
        }
        if(path == null){
            throw new RuntimeException(ex);
        }else{
            System.out.println("使用配置文件路径"+path);
            return new ClassPathResource(path);
        }
    }

    private String getConfigurePath() throws IOException {
        String path;
        String ip = NetworkUtils.getWideAreaIp();
        System.out.println("本地公网ip"+ip);
        if("45.98.23.90".equals(ip)){
            path = "properties/produce-common.properties";
        }else if("221.225.1.22".equals(ip)){
            path = "properties/test-common.properties";
        }else{
            path = "properties/dubbo.properties";
        }
        return path;
    }
}
